package com.autoagent.ai_live_master.scriptRecommendation.controller;

import com.autoagent.ai_live_master.common.base.ApiResponse;
import com.autoagent.ai_live_master.common.base.UserContext;
import com.autoagent.ai_live_master.common.model.PageRequestVO;
import com.autoagent.ai_live_master.common.utils.BeanConverter;
import com.autoagent.ai_live_master.scriptRecommendation.dto.ScriptConfigDTO;
import com.autoagent.ai_live_master.scriptRecommendation.entity.ScriptConfig;
import com.autoagent.ai_live_master.scriptRecommendation.service.ScriptConfigService;
import com.autoagent.ai_live_master.scriptRecommendation.vo.ScriptConfigVO;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import java.util.List;

/**
 * <p>
 * 话术生成核心配置表 控制器
 * </p>
 *
 * @author TraeAI
 * @since 2024-07-26
 */
@Tag(name = "09-话术配置管理", description = "话术生成核心配置的创建、查询和管理相关接口")
@RestController
@RequestMapping("/script-config")
@RequiredArgsConstructor
@Slf4j
public class ScriptConfigController {

    private final ScriptConfigService scriptConfigService;

    /**
     * 创建话术配置
     *
     * @param scriptConfigVO 话术配置VO
     * @return 创建后的话术配置DTO
     */
    @Operation(summary = "创建话术配置", description = "创建电商话术推荐配置，用于直播中按特定策略推荐商品话术")
    @PostMapping
    public ApiResponse<ScriptConfigDTO> createScriptConfig(
            @Parameter(description = "话术配置信息", required = true)
            @RequestBody @Valid ScriptConfigVO scriptConfigVO) {
        log.info("创建话术配置: {}", scriptConfigVO);
        
        try {
            // 使用BeanConverter转换VO为实体，并设置用户ID
            ScriptConfig scriptConfig = BeanConverter.convert(scriptConfigVO, ScriptConfig.class);
            scriptConfig.setUserId(UserContext.getCurrentUserId());
            
            // 使用BeanConverter转换为DTO并调用服务层
            ScriptConfigDTO createdConfig = scriptConfigService.createScriptConfig(scriptConfig);
            
            return ApiResponse.success("创建话术配置成功", createdConfig);
        } catch (RuntimeException e) {
            log.error("创建话术配置失败: {}", e.getMessage(), e);
            return ApiResponse.error(500, "创建话术配置失败: " + e.getMessage());
        }
    }

    /**
     * 获取当前用户的所有话术配置
     *
     * @return 话术配置DTO列表
     */
    @Operation(summary = "获取话术配置列表", description = "分页获取当前登录用户的所有话术推荐配置，支持按配置名称模糊搜索")
    @GetMapping("/list")
    public ApiResponse<Page<ScriptConfigDTO>> getScriptConfigsByUserId(@ModelAttribute PageRequestVO pageRequest) {
        Long userId = UserContext.getCurrentUserId();
        log.info("获取用户话术配置列表 - 用户ID: {}, 页码: {}, 每页大小: {}, 关键字: {}",
                userId, pageRequest.getPageNum(), pageRequest.getPageSize(), pageRequest.getKeyword());

        try {
            Page<ScriptConfigDTO> scriptConfigs = scriptConfigService.getPageByUserId(
                    userId,
                    pageRequest.getPageNum(),
                    pageRequest.getPageSize(),
                    pageRequest.getKeyword());
            log.info("获取用户话术配置列表成功, 用户ID: {}, 配置数量: {}", userId, scriptConfigs.getTotal());
            return ApiResponse.success(scriptConfigs);
        } catch (RuntimeException e) {
            log.error("获取用户话术配置列表失败: {}", e.getMessage(), e);
            return ApiResponse.error(500, "获取用户话术配置列表失败: " + e.getMessage());
        }
    }

    /**
     * 更新话术配置
     *
     * @param id 话术配置ID
     * @param scriptConfigVO 话术配置VO
     * @return 更新后的话术配置DTO
     */
    @Operation(summary = "更新话术配置", description = "更新指定ID的话术推荐配置")
    @PutMapping("/{id}")
    public ApiResponse<ScriptConfigDTO> updateScriptConfig(
            @Parameter(description = "话术配置ID", required = true)
            @PathVariable Integer id,
            @Parameter(description = "话术配置信息", required = true)
            @RequestBody @Valid ScriptConfigVO scriptConfigVO) {
        log.info("更新话术配置, ID: {}, 数据: {}", id, scriptConfigVO);
        
        try {
            // 使用BeanConverter转换VO为实体，并设置ID和用户ID
            ScriptConfig scriptConfig = BeanConverter.convert(scriptConfigVO, ScriptConfig.class);
            scriptConfig.setId(id);
            scriptConfig.setUserId(UserContext.getCurrentUserId());
            
            // 使用BeanConverter转换为DTO并调用服务层
            ScriptConfigDTO updatedConfig = scriptConfigService.updateScriptConfig(scriptConfig);
            
            return ApiResponse.success("更新话术配置成功", updatedConfig);
        } catch (RuntimeException e) {
            log.error("更新话术配置失败: {}", e.getMessage());
            return ApiResponse.error(404, e.getMessage());
        }
    }

    /**
     * 删除话术配置
     *
     * @param id 话术配置ID
     * @return 无内容响应
     */
    @Operation(summary = "删除话术配置", description = "删除指定的话术推荐配置")
    @DeleteMapping("/{id}")
    public ApiResponse<String> deleteScriptConfig(
            @Parameter(description = "话术配置ID", required = true)
            @PathVariable Integer id) {
        log.info("删除话术配置, ID: {}", id);
        try {
            boolean deleted = scriptConfigService.deleteScriptConfig(id);
            return ApiResponse.success("删除话术配置成功", null);
        } catch (RuntimeException e) {
            log.error("删除话术配置失败: {}", e.getMessage());
            return ApiResponse.error(404, e.getMessage());
        }
    }
}